<?php

namespace App\Admin\Actions\NewsAction;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use OpenAI;

class NewsBriefCreate extends RowAction
{
    public $name = '生成新摘要';
    
    public function handle(Model $model)
    {
	    /**
	     * @var $model User
	     */
    	

	    $yourApiKey = getenv('CHATGPT_API_KEY');
	   
		//$client = OpenAI::client($yourApiKey);

		$data = [];

		if($model->title_cn && $model->content_cn){

			$titleContent = [
			    'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是一个新闻工作者"],
			        ['role' => 'user', 'content' => '将标题【'.$model->title_cn.'】和内容【'.$model->content_cn.'】重新解读，要求简练清晰，观点明确, 将数据量化，返回内容不超过50字，不需要注明文章来源'],
			    ],
			    'max_tokens' => 150
			]; 

			$titleResult = $this->curl($titleContent);
			
			$titleResult = json_decode($titleResult,true);

			//$title = $titleResult['choices'][0]['message']['content'];


			if(strlen($titleResult['choices'][0]['message']['content'])>50){

				$titleContent = [
				    'model' => 'gpt-3.5-turbo',
				    'messages' => [
				    	['role' => 'system', "content"=> "你是一个新闻工作者"],
				        ['role' => 'user', 'content' => '将标题【'.$model->title_cn.'】和内容【'.$model->content_cn.'】重新解读，要求简练清晰，观点明确, 将数据量化，返回内容不超过50字，不需要注明文章来源'],
				        ['role' => 'system', 'content' => $titleResult['choices'][0]['message']['content']],
				        ['role' => 'user', 'content' => '再简化一下，不超过50字'],
				    ],
				    'max_tokens' => 60
				]; 

				$titleResult = $this->curl($titleContent);
			
				$titleResult = json_decode($titleResult,true);

			}



			$data['brief'] = $titleResult['choices'][0]['message']['content']; 
			
		}elseif($model->source == 'scmp'){

				$titleContent = [
				    'model' => 'gpt-3.5-turbo',
				    'messages' => [
				    	['role' => 'system', "content"=> "你是一个新闻工作者"],
				        ['role' => 'user', 'content' => '将标题【'.$model->title_zn.'】和内容【'.$model->content_zn.'】重新解读，要求简练清晰，观点明确, 将数据量化，返回内容不超过100字，不需要注明文章来源，返回内容为英文,去掉html标签'],
				    ],
				    'max_tokens' => 150
				]; 
				$titleResult = $this->curl($titleContent);
			
				$titleResult = json_decode($titleResult,true);

				$data['brief_zn'] = $titleResult['choices'][0]['message']['content']; 
		}
 		
		

		 $model->update($data);
	  
    	
    	
	    return $this->response()->success('摘要生成完成')->refresh();
    }

    public function curl($data){

		$curl = curl_init();
		$data = json_encode($data);


		curl_setopt_array($curl, array(
		   CURLOPT_URL => 'https://api.chatanywhere.com.cn/v1/chat/completions',
		   CURLOPT_RETURNTRANSFER => true,
		   CURLOPT_ENCODING => '',
		   CURLOPT_MAXREDIRS => 10,
		   CURLOPT_TIMEOUT => 0,
		   CURLOPT_FOLLOWLOCATION => true,
		   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		   CURLOPT_CUSTOMREQUEST => 'POST',
		   CURLOPT_POSTFIELDS =>$data,
		   CURLOPT_HTTPHEADER => array(
		      'Authorization: Bearer '.env('CHATGPT_API_KEY'),
		      'User-Agent: Apifox/1.0.0 (https://apifox.com)',
		      'Content-Type: application/json'
		   ),
		));

	   $response = curl_exec($curl);

	   //dd($response);
	   return $response;
	}

	
	public function dialog()
	{
		$this->confirm('确定生成该文章摘要吗?');
	}
}
